package com.tzu.ft.transfer.server;

import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.TrustManagerFactory;

import com.tzu.ft.base.TransferTools;
import com.tzu.ssl.KeyInfo;
import com.tzu.ssl.SSLTools;

/**
 * * 服务端，ssl
 */
public class FTSSLServer extends Server {

	/**
	 * <ul>
	 * <li>ssl连接的重点:</li>
	 * <li>初始化SSLServerSocket</li>
	 * <li>导入服务端私钥KeyStore，导入服务端受信任的KeyStore(客户端的证书)</li>
	 * </ul>
	 */
	@Override
	public void init(int port, KeyInfo keyInfo) {
		this.port = port;
		try {
			char[] password = keyInfo.getKeypass().toCharArray();

			KeyStore ks = KeyStore.getInstance(keyInfo.getKeyStoreType());
			ks.load(new FileInputStream(keyInfo.getKeyStorePath()), password);
			KeyManagerFactory kmf = KeyManagerFactory.getInstance(SSLTools.SUN_X509);
			kmf.init(ks, password);

			KeyStore tks = KeyStore.getInstance(keyInfo.getKeyStoreType());
			TrustManagerFactory tmf = TrustManagerFactory.getInstance(SSLTools.SUN_X509);
			tks.load(new FileInputStream(keyInfo.getTrustStorePath()), password);
			tmf.init(tks);

			SSLContext ctx = SSLContext.getInstance(keyInfo.getSslVersion());
			// ctx.init(kmf.getKeyManagers(), null, null); // 单向验证
			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

			SSLServerSocket sslServerSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(port);
			sslServerSocket.setNeedClientAuth(true); // false或者不设置则为单向验证
			sslServerSocket.setSoTimeout(TransferTools.DEFAULT_SO_TIMEOUT);
			//赋值
			serverSocket = sslServerSocket;
//			serverSocket.setReceiveBufferSize(BUFFER_SIZE);
			serverSocket = TransferTools.settingServerSocket(serverSocket);

			System.out.println(
					"启动服务：" + serverSocket.getInetAddress().getHostAddress() + ":" + serverSocket.getLocalPort());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



	//=========================================================================
	public static void main(String[] args) throws Exception {
		FTSSLServer server = new FTSSLServer();
//        server.init("HT304*20201008");
//		server.start();
	}

}
